<?php

namespace dk\widget;
use dk\widget\Js;
use dk\widget\Css;

class Head extends Base {
    use \dk\widget\Singleton;

    private $css = [];
    private $js = [];
    private $charset;
    private $metas = [];

    protected static $sended = false;

    /**
     * @param \weixin\core\View $plug
     */
    function bindHandle($plug) {
        $plug->regPlug('head', array($this, 'render'));
    }

    public function addCssFile($file){
        if(is_array($file)){
            $this->css = array_merge($this->css, $file);
        }else{
            $this->css[] = $file;
        }
        return $this;
    }

    public function addJsFile($file){
        if(is_array($file)){
            $this->js += $file;
        }else{
            $this->js[] = $file;
        }
        return $this;
    }

    public function charset($charset){
        $this->charset = $charset;
        return $this;
    }

    public function addMetas($string){
        $this->metas[] = $string;
        return $this;
    }

    public function addHtml($string, $index = null){
        if($index){
            $this->metas[$index] = $string;
        }else{
            $this->metas[] = $string;
        }
        return $this;
    }

    public function render(){
        self::$sended = true;

        $html = $this->metas;
        if($this->charset){
            $html[] = '<meta charset="' . $this->charset . '">';
        }
        $html[] = Css::getInstance()->printFiles($this->css);
        $html[] = Js::getInstance()->printJSFile($this->js);

        return implode("\r\n", $html);
    }

    public static function isSend(){
        return self::$sended;
    }
}